package com.ruoyi.student.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.student.domain.vo.RegInfo;
import com.ruoyi.student.domain.vo.StudentRegVo;
import com.ruoyi.student.service.IStudentInfoService;
import com.ruoyi.student.service.ISysRegistryTimeService;
import com.ruoyi.student.service.StudentRegistrationImportService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.student.domain.StudentRegistration;
import com.ruoyi.student.service.IStudentRegistrationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生注册Controller
 * 
 * @author ruoyi-mate
 * @date 2025-08-11
 */
@RestController
@RequestMapping("/student/registration")
public class StudentRegistrationController extends BaseController
{
    @Autowired
    private IStudentRegistrationService studentRegistrationService;
    @Autowired
    private StudentRegistrationImportService studentRegistrationImportService;
    @Autowired
    private IStudentInfoService studentInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;

    // 新增：注入注册时间服务
    @Autowired
    private ISysRegistryTimeService registryTimeService;
    /**
     * 查询学生注册列表
     */
    //@PreAuthorize("@ss.hasPermi('student:registration:list')")
    @GetMapping("/list")
    public TableDataInfo list(StudentRegistration studentRegistration)
    {
        startPage();
        List<StudentRegistration> list = studentRegistrationService.selectStudentRegistrationList(studentRegistration);
        return getDataTable(list);
    }

    /**
     * 导出学生注册列表
     */
/*    @PreAuthorize("@ss.hasPermi('student:registration:export')")*/
    @Log(title = "学生注册", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentRegistration studentRegistration)
    {
        List<StudentRegistration> list = studentRegistrationService.selectStudentRegistrationList(studentRegistration);
        ExcelUtil<StudentRegistration> util = new ExcelUtil<StudentRegistration>(StudentRegistration.class);
        util.exportExcel(response, list, "学生注册数据");
    }

    /**
     * 获取学生注册详细信息
     */
 /*   @PreAuthorize("@ss.hasPermi('student:registration:query')")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(studentRegistrationService.selectStudentRegistrationById(id));
    }

    /**
     * 新增学生注册
     */
/*    @PreAuthorize("@ss.hasPermi('student:registration:add')")*/
    @Log(title = "学生注册", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StudentRegistration studentRegistration)
    {
        return toAjax(studentRegistrationService.insertStudentRegistration(studentRegistration));
    }

    /**
     * 修改学生注册
     */
/*    @PreAuthorize("@ss.hasPermi('student:registration:edit')")*/
    @Log(title = "学生注册", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StudentRegistration studentRegistration)
    {
        return toAjax(studentRegistrationService.updateStudentRegistration(studentRegistration));
    }

    /**
     * 删除学生注册
     */
/*    @PreAuthorize("@ss.hasPermi('student:registration:remove')")*/
    @Log(title = "学生注册", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(studentRegistrationService.deleteStudentRegistrationByIds(ids));
    }
/*    @PreAuthorize("@ss.hasPermi('student:registration:remove')")*/
    @Log(title = "学生注册", businessType = BusinessType.EXPORT)
    @DeleteMapping("/deleteAll")
    public AjaxResult deleteAll(){
        return toAjax(studentRegistrationService.deleteAll());
    }
    /**
     * 启动学生注册信息导入任务
     */
    @PostMapping("/start")
    public AjaxResult startImport() {
        // 生成唯一批次号
        String batchNo = IdUtils.fastUUID();
        // 调用异步导入方法
        studentRegistrationImportService.doImport(batchNo);
        // 立即返回批次号，前端可通过此批次号查询进度
        return AjaxResult.success("导入任务已启动", batchNo);
    }

    /**
     * 查询导入进度
     */
    @GetMapping("/progress/{batchNo}")
    public AjaxResult getImportProgress(@PathVariable String batchNo) {
        return AjaxResult.success(studentRegistrationImportService.getImportProgress(batchNo));
    }
    /**
     * 获取当前浏览器信息和ip地址信息返回到前端显示
     */
    @GetMapping("/browserInfo")
    public AjaxResult getBrowserInfo() {
        // 获取当前登录用户
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null) {
            return AjaxResult.error("未获取到登录用户信息");
        }
        // 获取当前登录IP地址
        RegInfo regInfo = new RegInfo();
        regInfo.setIp(user.getIpaddr());
        regInfo.setBrowser(user.getBrowser());
        regInfo.setOs(user.getOs());
        // 封装返回结果
        return AjaxResult.success("new Object[]{browser, os, ip}",regInfo);
    }
    /*
    查询VO返回前端显示学生个人数据信息
    * */
    @GetMapping("/search")  // 修复拼写错误：serach -> search
    public AjaxResult search() {
        // 获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user == null) {
            return AjaxResult.error("未获取到登录用户信息");
        }
        // 调用服务层方法查询学生信息（修复方法名拼写错误）
        StudentRegVo studentRegVo = studentInfoService.getStudentReVoByStudentId(user.getUserName());
        if (studentRegVo == null) {
            return AjaxResult.warn("未查询到对应学生信息");
        }
        return AjaxResult.success(studentRegVo);
    }



    /**
     * 新增接口：检查当前是否在注册时间段内
     */
    @GetMapping("/checkTime")
    public AjaxResult checkRegistryTime() {
        boolean inTime = registryTimeService.isInRegistryTime();
        String timeDesc = registryTimeService.getRegistryTimeDesc();
        return AjaxResult.success().put("inTime", inTime).put("timeDesc", timeDesc);
    }

    /*
    *点击注册判断ip定位如果ip不在允许范围内则提示用户
    *  */
    /*
     * 点击注册判断ip定位如果ip不在允许范围内则提示用户
     * */
    @PostMapping("/checkIP")
    public AjaxResult checkIP() {
        // 1. 先判断是否在注册时间段（原有逻辑保留）
        if (!registryTimeService.isInRegistryTime()) {
            return AjaxResult.error("当前不在注册时间段内，注册时间为：" + registryTimeService.getRegistryTimeDesc());
        }

        // 2. 获取当前登录用户（原有逻辑保留）
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null) {
            return AjaxResult.error("未获取到登录用户信息");
        }
        String studentId = user.getUsername(); // 学号（登录用户名）

        // 3. 查询学生注册记录（原有逻辑保留）
        StudentRegistration student = studentRegistrationService.selectStudentRegistrationByStudentId(studentId);
        if (student == null) {
            return AjaxResult.error("未查询到对应学生注册信息");
        }

        // 4. 获取登录IP（原有逻辑保留，优化冗余对象创建）
        String loginIp = IpUtils.getIpAddr(); // 直接调用静态方法，无需 new IpUtils()
        System.out.println("登录IP：" + loginIp + "，登录用户：" + studentId);
        if (loginIp == null || loginIp.isEmpty()) {
            return AjaxResult.error("无法获取登录IP地址");
        }

        // 5. 检查IP是否在允许范围（原有逻辑保留）
        List<String> allowedIpSegments = Arrays.asList(
                "192.168.1.", "10.0.0.", "172.16.31.", "127.0.0.1","10.20."  // 新增：允许 10.20.x.x 网段（包含你的 10.20.79.86）
        );
        boolean isAllowed = allowedIpSegments.stream()
                .anyMatch(segment -> loginIp.startsWith(segment));

        if (isAllowed) {
            // 6. 构建更新对象（优化：直接用查询到的 student 赋值，去除冗余查询）
            StudentRegistration updateReg = new StudentRegistration();
            updateReg.setId(student.getId());          // 注册记录ID
            updateReg.setRegistrationIp(loginIp);      // 注册IP
            updateReg.setRegistrationTime(new Date()); // 注册时间
            updateReg.setBrowserInfo(user.getBrowser());// 浏览器信息
            updateReg.setOsInfo(user.getOs());         // 操作系统信息
            updateReg.setRegistrationStatus(1);        // 状态：1=已通过（需和前端映射一致）
            updateReg.setUpdateTime(new Date());       // 更新时间

            // 7. 第一步：更新 student_registration 表（注册记录）
            int regUpdateCount = studentRegistrationService.updateStudentRegistration(updateReg);
            if (regUpdateCount <= 0) {
                return AjaxResult.error("注册失败：更新注册记录失败");
            }

            // 8. 第二步：同步更新 student_info 表（学生状态文本，关键！）
            int infoUpdateCount = studentInfoService.updateStudentZcztByStudentId(studentId, "已通过");
            if (infoUpdateCount <= 0) {
                return AjaxResult.warn("注册记录已更新，但学生状态同步失败，请刷新页面重试");
            }

            // 9. 两处更新都成功，返回成功
            return AjaxResult.success("注册成功，状态已更新为“已通过”");
        } else {
            return AjaxResult.error("当前IP地址不在允许的注册范围内，无法进行注册操作");
        }
    }
}
